package com.engine.yhzc.sync.util;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.addons.common.constant.ResultCode;
import com.engine.addons.common.entity.ResultMsg;
import com.engine.addons.common.util.FastJsonUtil;
import com.engine.addons.common.util.LogUtil;
import com.engine.addons.common.util.PropertiesUtil;
import com.engine.addons.common.util.StringUtil;
import com.engine.addons.init.config.constant.ValueType;
import com.engine.addons.init.dataProcess.entity.*;
import com.engine.ch.service.impl.SyncArchiveImpl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FixedAssetsSyncUtil {
    private static final Log log = LogFactory.getLog(FixedAssetsSyncUtil.class);
    public static ResultMsg<String> callSync(String dto) {

        ResultMsg<String> resultMsg = new ResultMsg<>(ResultCode.NotFound);

        try {


            PropertiesUtil prop = new PropertiesUtil();
            String url = prop.readProperty("fixedAssets.url");
            String apiPath = prop.readProperty("fixedAssets.api_path");
            JSONObject requestBody = new JSONObject(true);
            requestBody.put("dto", dto);
            // 构建请求参数
            JSONObject reqJson = new JSONObject(true);
            reqJson.put("api_method", "POST");
            reqJson.put("request_body", requestBody);
            reqJson.put("api_path", apiPath);
            log.info("同步url：" + url);
            String resStr = HttpRequest.post(url).body(reqJson.toJSONString()).execute().body();
            log.info("设备新建返回：" + resStr);
            if (StringUtil.isNull(resStr)) {
                resultMsg.setText("新建失败，返回为空");
                return resultMsg;
            }

            JSONObject resJson = JSONObject.parseObject(resStr);
            JSONArray returnInfo = resJson.getJSONArray("ReturnInfo");
            if (returnInfo == null) {
                resultMsg.setText("新建失败，返回为空");
                return resultMsg;
            }
            for (int a = 0; a < returnInfo.size(); a++) {
                JSONObject returnInfoJson = returnInfo.getJSONObject(a);
                Boolean msgSuccess = returnInfoJson.getBoolean("msgSuccess");
                if (!msgSuccess) {
                    resultMsg.setText("新建失败:"  + returnInfoJson.getString("message"));
                    return resultMsg;
                }
            }
            resultMsg.setCode(ResultCode.SUCCESS.getCode());
            resultMsg.setObject(resJson.getString("ReturnInfo"));
            return resultMsg;

        } catch (Exception e) {
            log.info("新建失败", e);
            resultMsg.setText("新建失败:" + e.getMessage());
            return resultMsg;
        }

    }
    public static JSONObject covertTableToJson(DataFormTable dataFormTable) {


        JSONObject resJson = new JSONObject(true);

        //主表
        MainTable main = dataFormTable.getFormTableList().get(0).getMaintableProcessData().get(0);
        List<Field> mainRow = main.getRow().getFields();
        double qty = 0;
        for (Field mainField : mainRow) {
            if(!"Qty".equals(mainField.getName())){
                continue;
            }
            qty = Double.parseDouble(mainField.getValue().toString());

        }
        for (int i = 0; i < qty; i++) {
            for (Field mainField : mainRow) {
                if("Qty".equals(mainField.getName())){
                    FastJsonUtil.setValue(resJson, mainField.getName(), 1);
                    continue;
                }
                if (mainField.getType() == null || !mainField.getType().equals(ValueType.VIRTUAL)) {

                    FastJsonUtil.setValue(resJson, mainField.getName(), mainField.getValue());
                }
            }

            //明细表
            List<DetailTable> detailtableTemp = dataFormTable.getFormTableList().get(0).getDetailtable();
            if (detailtableTemp != null && detailtableTemp.size() > 0) {

                //先根据明细表输出名合并明细表内容
                Map<String, List<Row>> dataMapList = new HashMap<>();
                for (DetailTable detailTable : detailtableTemp) {

                    String outputAlias = detailTable.getOutputAlias();
                    log.info("outputAlias：" + outputAlias);
                    if (!dataMapList.containsKey(outputAlias)) {
//                        dataMapList.get(outputAlias).addAll(detailTable.getRows());
//                    } else {
                        dataMapList.put(outputAlias, detailTable.getRows());
                    }
                }

                //循环明细表
                for (Map.Entry<String, List<Row>> entry : dataMapList.entrySet()) {

                    List<Row> dataRows = entry.getValue();

                    String outputAlias = entry.getKey();
                    JSONArray detailJson = new JSONArray();

                    for (Row dataRow : dataRows) {

                        JSONObject detailTemp = new JSONObject(true);

                        List<Field> fieldList = dataRow.getFields();
                        for (Field field : fieldList) {
                            if (field.getType() == null || !field.getType().equals(ValueType.VIRTUAL)) {

                                String fname = field.getName();
                                FastJsonUtil.setValue(detailTemp, fname, field.getValue());
                            }
                        }

                        detailJson.add(detailTemp);
                    }

                    FastJsonUtil.setValue(resJson, outputAlias, detailJson);

                }
            }
        }
        log.info("resJson："+resJson);
        return resJson;
    }
}
